package com.franklin.ideaplugin.api.ui.table;

import cn.hutool.core.collection.CollectionUtil;
import com.google.common.collect.Lists;
import lombok.Getter;

import javax.swing.table.DefaultTableModel;
import java.util.List;

/**
 * 抽象TableModel
 * @author Franklin
 * @since 2021/08/28 09:47
 */
@Getter
public abstract class AbstractTableModel<T> extends DefaultTableModel {

    private List<T> rowList;

    public AbstractTableModel() {
        String[] headerNames = this.headerNames();
        for (String headerName : headerNames) {
            super.addColumn(headerName);
        }
        this.rowList = Lists.newArrayList();
    }

    public void refresh(List<T> rowList){
        if (CollectionUtil.isNotEmpty(rowList)){
            this.removeAllRow();
            this.rowList = rowList;
            rowList.forEach(row -> super.addRow(toArray(row)));
        }
    }

    private void removeAllRow(){
        int rowCount = this.getRowCount();
        for (int i = 0; i < rowCount; i++) {
            super.removeRow(0);
        }
    }

    @Override
    public void removeRow(int row) {
        super.removeRow(row);
        this.rowList.remove(row);
    }

    public void addRow(T rowData){
        super.addRow(this.toArray(rowData));
        this.rowList.add(rowData);
    }

    @Override
    public void setValueAt(Object aValue, int row, int column) {
        super.setValueAt(aValue, row, column);
        T obj = this.rowList.get(row);
        this.setVal(obj,column, aValue);
    }

    protected abstract String[] headerNames();

    protected abstract Object[] toArray(T rowData);

    protected abstract <E> void setVal(T rowData,int columnIndex,E value);
}
